package cn.tedu.zblogs.home.utils;

import com.alibaba.cloud.commons.io.IOUtils;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * Json工具类
 * 对象转为json
 * json转为对象
 */
public class JsonUtils {


    /**
     * 定义对象转换Json工具 ObjectMapper StringBoot的默认 json 工具 Jackson
     */
    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * java对象转换为Json
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        //没有必要每次调用toJson方法都 new 一个 ObjectMapper对象
        //占用jvm的内存空间 可以搞成单例,全局只有一个ObjectMapper对象
        //ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * json 转换为 java 对象
     * @param json
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T fromJson(String json,Class<T> clazz) {
        try {
            return mapper.readValue(json,clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static JSONObject fileToJson(String fileName) {
        JSONObject json = null;
        try (
                InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
        ) {
            json = JSONObject.parseObject(IOUtils.toString(is, Charset.defaultCharset()));
        } catch (Exception e) {
            System.out.println(fileName + "文件读取异常" + e);
        }
        return json;
    }

    public static String fileToJsontoString(String fileName) {
        String json = null;
        try (
                InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
        ) {
            json = IOUtils.toString(is, Charset.defaultCharset());
        } catch (Exception e) {
            System.out.println(fileName + "文件读取异常" + e);
        }
        return json;
    }
}



